FIFO Queues In .NET

1 min read
Foundational1 min read
Rapid overview

FIFO Queues In .NET

TL;DR

A FIFO queue processes items in the order they were added — first in, first out. The interview trap is the naive array implementation: Array.push + Array.shift makes dequeue O(n) because every remaining element shifts down. The fix is a head pointer (or a real linked-list/ring-buffer queue) so both enqueue and dequeue stay O(1).

How it works


Simple queue

const queue: string[] = [];
queue.push('a');
queue.push('b');
const first = queue.shift();

Efficient queue

For large queues, avoid shift (O(n)). Use a pointer.

class Queue<T> {
  private items: T[] = [];
  private head = 0;

  enqueue(item: T) { this.items.push(item); }
  dequeue(): T | undefined {
    if (this.head >= this.items.length) return undefined;
    const item = this.items[this.head];
    this.head += 1;
    return item;
  }
}

Interview prompt

  • Why is shift() slow for large arrays, and how do you avoid it?

See also